﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MLM.Data;
using MLM.AdminCP.Class;
using MLM.Base;

namespace MLM.AdminCP.Pages
{
    public partial class ResetDistributorPassword : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            Permission.CheckIsAdmin();
            base.OnInit(e);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Permission.CheckIsAdmin();
            btnViewPassword.Click += new EventHandler(btnViewPassword_Click);
            btnResetPass.Click += new EventHandler(btnResetPass_Click);
        }

        void btnViewPassword_Click(object sender, EventArgs e)
        {
            MLMDataContext ct = new MLMDataContext();
            var _userId = long.Parse(UserIDTxt.Text);
            try
            {
                NewPasswordTxt.Text = ct.Users.FirstOrDefault(it => it.UserId == _userId).Password;
            }
            catch (Exception)
            {
                Message.ShowError("Error! UserID not found!");
            }
        }

        void btnResetPass_Click(object sender, EventArgs e)
        {
            MLMDataContext ct = new MLMDataContext();
            var _userId = long.Parse(UserIDTxt.Text);
            try
            {
                ct.Users.FirstOrDefault(it => it.UserId == _userId).Password = NewPasswordTxt.Text;
                ct.SaveChanges();
                try
                {
                    Email.Send_Email(ct.UserInfos.FirstOrDefault(it => it.UserID == _userId).Email, "Password reset",
                                     CommonSettingHelper.GetCommonSetting(ct,
                                         CommonSettingsContstants.EMAIL_SENDNEWPASSWORDTEMPLATE).Replace("{{USER_PASSWORD}}",NewPasswordTxt.Text.Trim()));
                }
                catch (Exception)
                {

                }
                Message.ShowSuccess("Password changed!");
            }
            catch (Exception ex)
            {
                Message.ShowError(ex.Message);
            }
        }
    }
}